<?php
class RequestDelegate
{/*{{{*/
    const TIME_OUT = 3;

    static public function requestByProxy($proxy, $urlInfo, $params=array(), $timeout=3)
    {/*{{{*/
        $request = self::parseUrl($urlInfo) . self::parseParams($params);

        $ch = curl_init();

        $proxyUrl = self::parseUrl($proxy);
        $header = array('Cache-Control: no-cache');
        curl_setopt($ch, CURLOPT_PROXY, $proxyUrl);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

        curl_setopt($ch, CURLOPT_URL, $request);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);

        return $response;
    }/*}}}*/

    public static function request($urls, $method='get', $args='', $timeout=15)
    {/*{{{*/
        $url = self::pickupHost($urls);
        $ch = curl_init($url);
        if ('post' == $method)
        {
            $data = '';
            if(is_array($args))
            {
                foreach($args as $key=>$val)
                {
                    $data .="$key=".urlencode($val)."&";
                }
            }
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }

        //proxy
        /*
        $header = array('Cache-Control: no-cache');
        curl_setopt($ch, CURLOPT_PROXY, 'http://cache1.web.bjt.qihoo.net:80');
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        */

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_USERAGENT, 'User-AgentMozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3');
        $content = curl_exec($ch);

        $err = curl_error($ch);
        $err = curl_error($ch);
        if ('' != $err)
        {
            $log = LoggerManager::getLogger('curl');
            $msg = $url.' | '.$err;
            $log->debug($msg);
        }
        curl_close($ch);
        return $content;
    }/*}}}*/
    
    static private function pickupHost($hosts)
    {/*{{{*/
        if (is_array($hosts))
        {
            $key = array_rand($hosts);
            if (null !== $key)
            {
                $url = $hosts[$key];
                unset($hosts[$key]);
                return $url;
            }
            return '';
        }
        return $hosts;
    }/*}}}*/

    static public function multiRequest($requests, $timeout=3)
    {/*{{{*/
        $mh = curl_multi_init();

        foreach($requests as $request)
        {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $request);
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_multi_add_handle($mh, $ch);
            $conn[] = $ch;
        }
        do {
            $mrc = curl_multi_exec($mh, $active);
        } while($mrc == CURLM_CALL_MULTI_PERFORM);

        while ($active and $mrc == CURLM_OK)
        {
            if (curl_multi_select($mh) != -1)
            {
                do {
                    $mrc = curl_multi_exec($mh, $active);
                } while ($mrc == CURLM_CALL_MULTI_PERFORM);
            }
        }

        $cnt = count($requests);
        for($i =0; $i < $cnt; $i++)
        {
            if(!curl_errno($conn[$i]))
            {
                $res[$i] = curl_multi_getcontent($conn[$i]);
            }
            curl_multi_remove_handle($mh, $conn[$i]);
            curl_close($conn[$i]);
        }
        curl_multi_close($mh);

        return $res;
    }/*}}}*/

    static public function multiRequestByProxy($proxy, $requests, $timeout=3)
    {/*{{{*/
        $proxyUrl = self::parseUrl($proxy);
        $header = array('Cache-Control: no-cache');
        $mh = curl_multi_init();

        foreach($requests as $request)
        {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_PROXY, $proxyUrl);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            curl_setopt($ch, CURLOPT_URL, $request);
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_multi_add_handle($mh, $ch);
            $conn[] = $ch;
        }

        do {
            $mrc = curl_multi_exec($mh, $active);
        } while($mrc == CURLM_CALL_MULTI_PERFORM);

        while ($active and $mrc == CURLM_OK)
        {
            if (curl_multi_select($mh) != -1)
            {
                do {
                    $mrc = curl_multi_exec($mh, $active);
                } while ($mrc == CURLM_CALL_MULTI_PERFORM);
            }
        }

        $cnt = count($requests);
        for($i =0; $i < $cnt; $i++)
        {
            if(!curl_errno($conn[$i]))
            {
                $res[$i] = curl_multi_getcontent($conn[$i]);
            }
            curl_multi_remove_handle($mh, $conn[$i]);
            curl_close($conn[$i]);
        }
        curl_multi_close($mh);

        return $res;
    }/*}}}*/

    static public function parseUrl($urlInfo)
    {/*{{{*/
        $scheme = isset($urlInfo['scheme']) ? $urlInfo['scheme'] : 'http';
        $port = isset($urlInfo['port']) ? $urlInfo['port'] : 80;
        $path = isset($urlInfo['path']) ? $urlInfo['path'] : '';

        $request = $scheme . '://'. $urlInfo['host'] .':'. $port . $path;
        return $request;
    }/*}}}*/

    static public function parseParams($params)
    {/*{{{*/
        $paramString = '';
        $pairs = array();
        foreach($params as $key => $value)
        {
            $pair = $key .'='. $value;
            array_push($pairs, $pair);
        }
        if($query = implode('&', $pairs))
        {
            $paramString .= '?' . $query;
        }

        return $paramString;
    }/*}}}*/
}/*}}}*/

class ConfigLoader
{/*{{{*/
    static private $_configs=array();

    static public function getInstance()
    {
        static $ins;
        if (false == $ins instanceof self)
        {
            $ins = new self();
        }
        return $ins;
    }

    private function __construct()
    {
    }

    public function getConfig($property)
    {/*{{{*/
		if (array_key_exists($property, self::$_configs))
		{
			return self::$_configs[$property];
		}
		else 
		{
			include(Constants::QUC_PATH.'config/config.properties.php');
			$config = isset($$property)?$$property:'';
            self::$_configs[$property] = $config;
			return $config;
		}
    }/*}}}*/

    public function setConfig($property, $value)
    {
        self::$_configs[$property] = $value;
    }
}/*}}}*/

class Utility
{/*{{{*/
	//for example input ==> abc.jpg  return ==> jpg
	public static function getFileSuffix($fileName, $default='')
	{/*{{{*/
		$result = $fileName;
		$splitChar = ".";
		if(strrpos($result, $splitChar))
		{
			while(strrpos($result, $splitChar))
			{
				$result = substr($result, strrpos($result, $splitChar)+1);
			}
			return $result;
		}
		else
		{
			return $default;
		}
	}/*}}}*/

    static public function convertEncoding($arr, $toEncoding, $fromEncoding, $convertKey=false)
    {/*{{{*/
        if ($toEncoding == $fromEncoding)
        {
            return $arr;
        }
        if (is_array($arr))
        {
            $keys = array_keys($arr);
            for ($i=0,$max=count($keys);$i<$max;$i++)
            {
                $key = $keys[$i];
                $res = $arr[$key];
                if ($convertKey)
                {
                    unset($arr[$key]);
                    $key = mb_convert_encoding($key, $toEncoding, $fromEncoding);
                }

                if (is_array($res))
                {
                    $res = $this->_convertEncoding($res, $toEncoding, $fromEncoding, $convertKey);
                }
                else
                {
                    $res = mb_convert_encoding($res, $toEncoding, $fromEncoding);
                }

                $arr[$key] = $res;
            }
        }
        else
        {
            $arr = mb_convert_encoding($arr, $toEncoding, $fromEncoding);
        }
        return $arr;
    }/*}}}*/

    static public function setLocaleInfo($dir)
    {/*{{{*/
        $locale = 'zh_CN.UTF-8';
        $locale_dir = $dir.'locale/'; // your .po and .mo files should be at $locale_dir/$locale/LC_MESSAGES/messages.{po,mo}
        putenv("LANGUAGE=$locale");
        bindtextdomain('messages', $locale_dir);
        putenv("LANG=$locale");
        setlocale(LC_ALL, $locale);
        textdomain('messages');
    }/*}}}*/

    public static function filterKw($kw)
    {/*{{{*/
        if ('' != $kw)
        {
            $kw = mb_convert_encoding($kw, 'gbk', 'utf-8');
            $res = array();
            return ContentFilter::filterKw($kw, array('s'));
        }
        return false;
    }/*}}}*/

    static public function checkIsUpgrading()
    {/*{{{*/
        $ip = getenv('REMOTE_ADDR');
        if (Constants::IS_LAUNCHING && (Constants::CORP_IP != $ip))
        {
            header('Location: /upgrading.htm');
            exit;
        }
    }/*}}}*/

    static public function getHugeDataHelper($varName, $fileName)
    {/*{{{*/
        $ch = CacheHelper::getInstance(Constants::QUC_PATH);
        $$varName = $ch->get($varName);
        if (false == $$varName)
        {
            assert(is_file($fileName));
            include($fileName);
            $ch->set($varName, $$varName);
        }
        return $$varName;
    }/*}}}*/
}/*}}}*/
